//作者：唐源江

const express = require("express");
const db = require("../model/db");
const router = express.Router();
const Evaluation = db.Evaluation;

//添加评价
//作者：唐源江
router.post("/", async function (req, res) {
    const data = await Evaluation.create(req.body);
    res.send(data);
})

//删除评价
//作者：唐源江
router.delete("/:id", async function (req, res) {
    await Evaluation.deleteOne({
        _id: req.params.id
    })
    res.send(true);

})

//修改评价
//作者 唐源江
router.put("/:id", async (req, res) => {
    console.log(req.body)
    const data = await Evaluation.updateOne({
        _id: db.ObjectId(req.params.id)
    },req.body)
    res.send(true);
})

//查询所有评价
//作者 唐源江
router.get("/", async (req, res) => {
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let contion = {}; //条件对象
    if (req.query.key) {
        contion = {
            name: req.query.key.toUpperCase()
        }
    }
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");
        condition = {
            $or: [{
                    title: {
                        $regex: exp
                    }
                },
                {
                    content: {
                        $regex: exp
                    }
                },
                {
                    description: {
                        $regex: exp
                    }
                }
            ]
        };
    }
    const data = await db.Evaluation.find(condition).skip((page - 1) * limit).limit(limit);
    const count = await db.Evaluation.count(condition);
    res.send({
        "code": 0,
        "msg": "",
        "count": count,
        "data": data
    });
})

//查询单个评价
//作者 唐源江
router.get("/:id", async function (req, res) {
    console.log(req.params.id)
    const data = await Evaluation.findById(req.params.id);
    res.send(data);
})

//分页
//作者 唐源江
router.get("/", async (req, res) => {
    let condition = {};
    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            $or: [
                { name: { $regex: exp } },
                { type: { $regex: exp } }
            ]
        }
    }
    let page = parseInt(req.query.page);
    let limit = parseInt(req.query.limit);
    if (!page) {
        page = 1;
    }
    if (!limit) {
        limit = 10
    }
    const data = await Evaluation.find(condition).skip((page - 1) * limit).limit(limit);
    const count = await Evaluation.countDocuments(condition);
    res.send({
        "code": 0,
        "msg": "",
        "count": count,
        "data": data
    })
})
module.exports = router;